package com.linkage.educloud.ah.view.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.dl7.tag.TagView;
import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.config.AccountConfig;
import com.linkage.educloud.ah.config.AppConfig;
import com.linkage.educloud.ah.mvp.ABasicPresenter;
import com.linkage.educloud.ah.mvp.contract.ISplashContract;
import com.linkage.educloud.ah.mvp.presenter.SplashPresenter;
import com.linkage.educloud.ah.view.BasicFragment;
import com.linkage.educloud.ah.view.activity.MainActivity;
import com.linkage.educloud.ah.view.activity.login.LoginActivity;
import com.zzhou.common.library.util.DisplayUtils;
import com.zzhou.common.library.util.PermissionUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * <desc>
 * Created by The Moss on 2018/8/6.
 */

public class SplashFragment extends BasicFragment implements ISplashContract.IView, PermissionUtils.PermissionListener {
    @BindView(R.id.launcher_splash_iamge)
    ImageView mLuncherImage;
    @BindView(R.id.launcher_tag_skip)
    TagView mTagSkip;

    private ISplashContract.IPresenter iPresenter;
    private static final String[] permissionManifest = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };
    RequestOptions options = new RequestOptions()
            .centerCrop()
            .placeholder(R.mipmap.icon_default_bg)
            .error(R.mipmap.icon_default_bg)
            .priority(Priority.HIGH)
            .skipMemoryCache(true)//跳过内存缓存
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
    private CountDownTimer timer;

    public static SplashFragment newInstance() {
        return new SplashFragment();
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_splash;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        iPresenter = new SplashPresenter(getActivity(),this);
        initView(iPresenter);
//        initGuide();
        PermissionUtils.requestRunPermission(this, permissionManifest, this);
    }
    @Override
    protected void initView(ABasicPresenter iPresenter) {
        super.initView(iPresenter);
        String defaulBg = AppConfig.getInstance().getString(AppConfig.ShareKey.KEY_DEFAULT_SPLASH,"");
        Glide.with(getActivity()).load(defaulBg)
                .apply(options)
                .into(mLuncherImage);
        mTagSkip.setTagClickListener(new TagView.OnTagClickListener() {
            @Override
            public void onTagClick(int i, String s, int i1) {
                if (timer != null) {
                    timer.cancel();
                }
                doStips();
            }
        });
    }

    public void startStipsView() {
        // TODO: 2018/8/9 获取动态广告、获取用户信息自动登录
        getSplashBg();
        timer = new CountDownTimer(3000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mTagSkip.setText("跳过 " + (int) millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                doStips();
                mTagSkip.setText("跳过 0");
            }
        }.start();
    }
    private void getSplashBg(){
        new Thread() {
            @Override
            public void run() {
                int desityDpi = DisplayUtils.getDensityDpi(getActivity());
                int pic_type = 3;
                switch (desityDpi) {
                    case DisplayMetrics.DENSITY_LOW:
                    case DisplayMetrics.DENSITY_MEDIUM:
                        pic_type = 1;
                        break;
                    case DisplayMetrics.DENSITY_HIGH:
                        pic_type = 2;
                        break;
                    case DisplayMetrics.DENSITY_XHIGH:
                        pic_type = 3;
                        break;
                    case DisplayMetrics.DENSITY_400:
                    case DisplayMetrics.DENSITY_XXHIGH:
                    case DisplayMetrics.DENSITY_XXXHIGH:
                        pic_type = 4;
                        break;
                    default:
                        break;
                }
                iPresenter.getSplashBg(pic_type);
            }
        }.start();
    }
    private void autoLogin(){
        AccountData accountData = AccountConfig.getLastAccount();
//        iPresenter.autoLogin("13739277243", NativeHelper.MD5("123456"),3);
        if (accountData != null) {
            iPresenter.autoLogin(accountData.getLoginAccount(),accountData.getLoginpwd(),accountData.getUserType());
        }else{
            onLoginResult(false);
        }
    }
//    private void initGuide() {
//        boolean isGuide = AppConfig.getInstance().getBoolean(AppConfig.ShareKey.KEY_GUIDE, true);
//        if (isGuide) {
//            AppConfig.getInstance().putBoolean(AppConfig.ShareKey.KEY_GUIDE, false);
//            toSkipGuide();
//        } else {
//            PermissionUtils.requestRunPermission(this, permissionManifest, this);
//        }
//    }

    private void doStips() {
        autoLogin();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
//            PermissionUtils.requestRunPermission(this, permissionManifest, this);
//        }
//    }

    @OnClick(R.id.launcher_tag_skip)
    public void onClick() {
    }

//    private void toSkipGuide() {
//        super.onDestroy();
//        fragmentTransaction.replace(R.id.fragment_content, GuideFragment.newInstance(this), "guide")
//                .addToBackStack(GuideFragment.class.getSimpleName())
//                .commit();
//    }

    @Override
    public void onGetSplahResult(String picPath, int picKey) {
        AppConfig.getInstance().putString(AppConfig.ShareKey.KEY_DEFAULT_SPLASH,picPath);
        Glide.with(getActivity()).load(picPath)
                .apply(options)
                .into(mLuncherImage);
    }

    @Override
    public void onLoginResult(boolean isSuccess) {
        if (isSuccess) {
            MainActivity.launch(getActivity());
        }else{
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            getActivity().startActivity(intent);
            getActivity().finish();
        }
    }

    @Override
    public void onGranted() {
        AppConfig.getInstance().initialize();
        startStipsView();
    }

    @Override
    public void onDenied(List<String> permission) {
        if (permission.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                || permission.contains(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            PermissionUtils.openSettingActivity(getActivity(), "文件读写权限");
        } else if (permission.contains(Manifest.permission.READ_PHONE_STATE)) {
            PermissionUtils.openSettingActivity(getActivity(), "手机状态权限");
        } else {
            startStipsView();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.requestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
